#include"thread.h"
int sersend(const int netfd,MYSQL* mysql,sharInfo_t* info)
{  
    train_t train;
    char query[1024];
    bzero(&query,sizeof(query));
    char filename[1024];
    bzero(&filename,sizeof(filename));
    char cwd[1024];
    bzero(&cwd,sizeof(cwd));
    int changesize=1024*1024*100;
    int ret;
    bzero(&train,sizeof(train));

    //接收文件名
    recv(netfd,&train.length,sizeof(int),MSG_WAITALL);
    recv(netfd,&train.buf,train.length,MSG_WAITALL);
    remove_trailing_invisible_chars(train.buf);
    strcpy(filename,train.buf);

    //向sql发送指令判断文件是否存在
    int parID=info->parentID;
    if(parID==-1){
        parID=info->rootID;
    }
    sprintf(query, "SELECT md5 FROM df_mes WHERE fileName = '%s'and parID = %d and tomb=0 ;",filename,parID);
    printf("query = %s\n",query);
    mysql_query(mysql,query);
    MYSQL_RES* result=mysql_store_result(mysql);
    unsigned int row=mysql_num_rows(result);

    //如果不存在
    if(row==0){
        mysql_free_result(result);
        bzero(&train,sizeof(train));
        //向客户端发送-1代表服务器没有
        ret=-1;
        send(netfd,&ret,sizeof(int),MSG_NOSIGNAL);
        return -1;
    }
    //如果文件存在
    //向客户端发送0代表服务器存在该文件
    ret=0;
    send(netfd,&ret,sizeof(int),MSG_NOSIGNAL);

    //取出md5值
    MYSQL_ROW mysql_md5=mysql_fetch_row(result);
    char *md5=mysql_md5[0];

    getcwd(cwd,sizeof(cwd));
    strcat(cwd,"/storge/");
    strcat(cwd,md5);

    //打开该文件
    int fd=open(cwd,O_RDONLY);

    //发送文件长度
    struct stat statbuf;
    fstat(fd,&statbuf);
    bzero(&train,sizeof(train));
    train.length=(int)(statbuf.st_size);
    send(netfd,&train.length,sizeof(int),MSG_NOSIGNAL);
    
    
    if(train.length>changesize){
        ftruncate(fd,statbuf.st_size);
        char*p=(char*)mmap(NULL,statbuf.st_size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);

        //清空火车
        bzero(&train,sizeof(train_t));
        //接收发过来的截断长度
        recv(netfd,&train.length,sizeof(int),MSG_WAITALL);
        //如果接受的截断值不为0，从截断处开始发送文件，否则发送整个文件  
        if(train.length!=0){
            send(netfd,p+train.length,statbuf.st_size-train.length,MSG_NOSIGNAL);
        }else{
            send(netfd,p,statbuf.st_size,MSG_NOSIGNAL);
            munmap(p,statbuf.st_size);
        }
    }else{
        //清空火车
        bzero(&train,sizeof(train));
        //接收发过来的截断值
        recv(netfd,&train.length,sizeof(int),MSG_WAITALL);
        //如果接受的截断值不为0，从截断处开始发送文件，否则发送整个文件
        if(train.length!=0){
            lseek(fd,train.length-1,SEEK_SET);
            sendfile(netfd,fd,NULL,statbuf.st_size-train.length);
        }else{
            sendfile(netfd,fd,NULL,statbuf.st_size);
        }
    }

    mysql_free_result(result);
    return 0;
}

